import React, { useState, useEffect, useRef } from 'react';
import SearchList from '@/components/SearchList';
import { Table, Button, notification, Tooltip, Upload, message } from 'antd';
import { transFormIndex, showDeleteConfirm } from '@/utils/util';
import {
  EyeFilled,
  EditFilled,
  DeleteFilled,
  PlusCircleFilled,
  ExportOutlined,
  ImportOutlined,
  FileExcelOutlined,
} from '@ant-design/icons';
import API from '@/api/xjindex.js';
import { useModel, history } from 'umi';
import axios from 'axios';

// 固定资产
const PropertyManage = ({ isSelected, selectedKey }) => {
  // console.log(selectedKey)
  const { initialState } = useModel('@@initialState');
  const { userId, orgId } = initialState.info;
  const [dataSource, setDataSource] = useState([]);
  const [GDZCLX, setGDZCLX] = useState([]);
  const [orgList1, setOrgList1] = useState([]);
  const [params, setParams] = useState({
    assetName: '',
    affiliatedUnit: -1,
    assetType: -1,
    assetModel: '',
    deviceIp: '',
    orgId,
    deploymentLocation: '',
    procurementYears: '',
    pageNo: 1,
    pageSize: 10,
  });
  const [pagination, setPagination] = useState({
    total: 0, //总数
    pageSize: 10, //每页条数
    current: 1,
    showQuickJumper: true,
  });
  const searchList = [
    {
      name: 'assetName',
      title: '资产名称',
      type: 'input',
    },
    {
      name: 'assetType',
      title: '资产类型',
      type: 'select',
      otherProps: {
        options: GDZCLX,
      },
    },
    // {
    //   name: 'affiliatedUnit',
    //   title: '所属单位',
    //   type: 'select',
    //   otherProps: {
    //     options: orgList1,
    //   },
    // },
  ];

  if (isSelected) {
    params.affiliatedUnit = selectedKey;
  } else {
    params.affiliatedUnit = -1;
  }

  const pageSizeChange = (page) => {
    setParams({
      ...params,
      pageNo: page.current,
      pageSize: page.pageSize,
    });
  };
  const download = (filename, link) => {
    let DownloadLink = document.createElement('a');
    DownloadLink.style = 'display: none'; // 创建一个隐藏的a标签
    DownloadLink.download = filename;
    DownloadLink.href = link;
    document.body.appendChild(DownloadLink);
    DownloadLink.click(); // 触发a标签的click事件
    document.body.removeChild(DownloadLink);
  };
  const doExport = (params) => {
    return axios({
      url: '/jiaotong/assetFixed/AsExportExcel',
      method: 'post',
      data: params,
      headers: {
        jwt: localStorage.getItem('jwt'),
      },
      responseType: 'blob',
    })
      .then((res) => {
        console.log(res.data);
        if (res.data) {
          let fileUrl = window.URL.createObjectURL(res.data);
          download('固定资产导出表格', fileUrl);
          window.URL.revokeObjectURL(fileUrl);
        }
      })
      .catch((error) => {
        message.error('导出失败，请重试');
      });
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      render: (text, r, index) => transFormIndex(pagination, index),
    },
    {
      title: '资产名称',
      dataIndex: 'assetName',
      align: 'center',
    },
    {
      title: '所属单位',
      dataIndex: 'affiliatedUnit',
      align: 'center',
      render: (text) => {
        let a = {};
        orgList1.forEach((e) => {
          a[e.value] = e.label;
        });
        return a[text];
      },
    },
    {
      title: '资产类型',
      dataIndex: 'assetType',
      align: 'center',
      render: (text) => {
        let a = {};
        GDZCLX.forEach((e) => {
          a[e.value] = e.label;
        });
        return a[text];
      },
    },
    {
      title: '资产型号',
      dataIndex: 'assetModel',
      align: 'center',
    },
    {
      title: '设备IP',
      dataIndex: 'deviceIp',
      align: 'center',
    },
    {
      title: '采购年限',
      dataIndex: 'procurementYears',
      align: 'center',
    },
    {
      title: '部署位置',
      dataIndex: 'deploymentLocation',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'Operation',
      align: 'center',
      render: (text, record) => {
        return (
          <div>
            <Tooltip title="查看">
              <Button
                type="link"
                key="check"
                icon={<EyeFilled />}
                className="table-icon"
                onClick={checkLink.bind(null, record.id)}
              ></Button>
            </Tooltip>
            {record.createId == userId ? (
              <>
                <Tooltip title="编辑">
                  <Button
                    type="link"
                    key="edit"
                    icon={<EditFilled />}
                    className="table-icon"
                    onClick={editLink.bind(null, record.id)}
                  ></Button>
                </Tooltip>
                <Tooltip title="删除">
                  <Button
                    key="del"
                    type="link"
                    icon={<DeleteFilled />}
                    className="table-icon"
                    onClick={() => showDeleteConfirm(() => delFn(record.id))}
                  ></Button>
                </Tooltip>
              </>
            ) : (
              ''
            )}
          </div>
        );
      },
    },
  ];
  const delFn = (id) => {
    API.delAssetFixed({ id: id }).then((res) => {
      if (res) {
        notification.success({
          message: '删除成功',
        });
        initList(params);
      }
    });
  };

  function changParams(data) {
    setParams({
      ...data,
    });
  }

  const createLink = () => {
    history.push('/networkDefence/propertyManage/createGDZC'); //createFixedAsset
  };
  const editLink = (id) => {
    history.push({
      pathname: '/networkDefence/propertyManage/editGDZC',
      query: { id },
    });
  };
  const checkLink = (id) => {
    history.push({
      pathname: '/networkDefence/propertyManage/checkGDZC',
      query: { id },
    });
  };

  function initList(params = {}) {
    const dd = {
      assetName: '',
      affiliatedUnit: -1,
      assetType: -1,
      assetModel: '',
      deviceIp: '',
      deploymentLocation: '',
      procurementYears: '',
      pageNo: 1,
      pageSize: 10,
    };

    for (let d in dd) {
      if (params[d] === undefined) {
        params[d] = dd[d];
      }
    }
    API.getOrgList()
      .then((res) => {
        if (res) {
          setOrgList1(
            res.t.map((item) => {
              return {
                label: item.name,
                value: item.id,
              };
            }),
          );
        }
      })

      .then(() => {
        API.showAssetFixedList(params).then((res) => {
          if (res) {
            // console.log(res);
            const result = res.t.queryList.map((item) => {
              return {
                ...item,
              };
            });
            setDataSource(result);
            setPagination({
              ...pagination,
              total: res.t.totalSize, //总数
              current: res.t.currentPage,
              pageSize: res.t.pageSize,
            });
          }
        });
      });
  }

  const props = {
    name: 'file',
    action: '/jiaotong/assetFixed/AssetfixedImportExcel',
    headers: {
      jwt: localStorage.getItem('jwt'),
    },
    showUploadList: false,
    accept: '.xls,.xlsx',
    maxCount: 1,
    onChange(info) {
      if (info.file.status !== 'uploading') {
        // console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        // notification.success(`${info.file.name} `);
        if (info.file.response.code === '0001') {
          notification.success({ message: `${info.file.name}，文件导入成功` });
          initList();
        } else if (info.file.response.code === '0000') {
          notification.error({
            message: `文件导入失败，${info.file.response.desc}`,
          });
        }
      } else if (info.file.status === 'error') {
        notification.error({ message: '文件导入失败，请重试' });
      }
    },
  };

  const childRefs = useRef(null);
  //编辑列表
  const edictRow = (text) => {
    //打开编辑弹窗 调用子组件身上的方法打开
    childRefs.current.searchFn();
  };

  useEffect(() => {
    API.getGDZCLX().then((res) => {
      if (res) {
        const result = res.t.map((item) => {
          return {
            label: item.dictItemName,
            value: item.dictItemType,
          };
        });
        setGDZCLX(result);
      }
    });
  }, []);

  useEffect(() => {
    if (isSelected) {
      //   console.log(childRefs.current.searchFn());
      initList({ ...params, ...childRefs.current.searchFn() });
    }
  }, [params, selectedKey]);
  return (
    <>
      <SearchList
        ref={childRefs}
        searchList={searchList}
        initList={changParams}
      ></SearchList>
      <div className="bgf main-x">
        <div className="tools-x">
          <Button
            type="link"
            key="add"
            icon={<PlusCircleFilled />}
            className="btn-icon"
            onClick={createLink}
          >
            新增
          </Button>
          <Button
            type="link"
            key="export"
            onClick={doExport.bind(null, params)}
            download
            target="_blank"
            icon={<ExportOutlined />}
            className="btn-icon"
            disabled={dataSource.length === 0}
          >
            导出
          </Button>
          <Button
            type="link"
            className="btn-icon"
            href="/jiaotong/assetFixed/downloadTemplate"
            download
            target="_blank"
            key="model"
            icon={<FileExcelOutlined />}
          >
            模板
          </Button>
          <Upload {...props}>
            <Button
              type="link"
              key="import"
              icon={<ImportOutlined />}
              className="btn-icon"
            >
              导入
            </Button>
          </Upload>
        </div>
        <div>
          <Table
            columns={columns}
            rowKey="id"
            dataSource={dataSource}
            pagination={pagination}
            className="custom-table"
            onChange={pageSizeChange}
          ></Table>
        </div>
      </div>
    </>
  );
};

export default PropertyManage;
